package com.iraeta.api;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.iraeta.HikConfig;
import com.iraeta.uitl.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service(value = "HikAlarmApi")
public class HikAlarmApi {
    private static final Logger logger = LoggerFactory.getLogger(HikApi.class);

    @Autowired
    private HikConfig hikConfig;

    public final String  ARTEMIS_PATH = "/artemis";

    //告警信息
    public String getAlarmInfo(Date startTime , Date endTime) throws Exception{
        String url = ARTEMIS_PATH + "/api/els/v1/events/search";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", url); //Key 为协议，Value 为接口路径
            }
        };
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("pageNo", 1);
        jsonBody.put("pageSize", 1000);
        //查询时间段内数据
        jsonBody.put("startTime", Util.formatDateForHik(startTime));
        jsonBody.put("endTime", Util.formatDateForHik(endTime));
        String body = jsonBody.toJSONString();
        String result = ArtemisHttpUtil.doPostStringArtemis(new ArtemisConfig(hikConfig.getHost(), hikConfig.getAppkey(), hikConfig.getAppsecret()),
                path, body, null, null,"application/json;charset=UTF-8");
        if(StrUtil.isEmpty(result)){
            throw new RuntimeException("调用HIK接口[events/search]未知错误");
        }
        JSONObject jsonResult = JSONObject.parseObject(result);
        String code = jsonResult.getString("code");
        if(!code.equals("0")){
            throw new RuntimeException("调用HIK接口[events/search]错误:" + jsonResult.getString("msg"));
        }
        JSONObject jsonResultData = jsonResult.getJSONObject("data");
        return JSONObject.toJSONString(jsonResultData);
    }

}
